/**
 * Copyright 2014  XCL-Charts
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @Project XCL-Charts
 * @Description Android图表基类库
 * @author XiongChuanLiang<br></br>(xcl_168@aliyun.com)
 * @Copyright Copyright (c) 2014 XCL-Charts (www.xclcharts.com)
 * @license http://www.apache.org/licenses/  Apache v2 License
 * @version 1.0
 */
package com.demo.xclcharts.view

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.util.Log
import android.view.MotionEvent
import org.xclcharts.chart.LineChart
import org.xclcharts.chart.LineData
import org.xclcharts.renderer.XEnum
import java.util.LinkedList

/**
 * @ClassName LineChart01View
 * @Description  折线图的例子
 * @author XiongChuanLiang<br></br>(xcl_168@aliyun.com)
 */
class LineChart01View : DemoView {
    private val TAG = "LineChart01View"
    private val chart = LineChart()

    //标签集合
    private val labels = LinkedList<String>()
    private val chartData = LinkedList<LineData>()
    private val mPaintTooltips = Paint(Paint.ANTI_ALIAS_FLAG)

    constructor(context: Context?) : super(context) {
        // TODO Auto-generated constructor stub
        initView()
    }

    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {
        initView()
    }

    constructor(context: Context?, attrs: AttributeSet?, defStyle: Int) : super(
        context,
        attrs,
        defStyle
    ) {
        initView()
    }

    private fun initView() {
        chartLabels()
        chartDataSet()
        chartRender()

        //綁定手势滑动事件
        this.bindTouch(this, chart)
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        //图所占范围大小
        chart.setChartRange(w.toFloat(), h.toFloat())
    }

    private fun chartRender() {
        try {

            //设置绘图区默认缩进px值,留置空间显示Axis,Axistitle....		
            val ltrb = barLnDefaultSpadding
            chart.setPadding(
                ltrb[0].toFloat(),
                ltrb[1].toFloat(),
                ltrb[2].toFloat(),
                ltrb[3].toFloat()
            )

            //限制Tickmarks可滑动偏移范围
            chart.setXTickMarksOffsetMargin(ltrb[2] - 20f)
            chart.setYTickMarksOffsetMargin(ltrb[3] - 20f)


            //显示边框
            chart.showRoundBorder()


            //设定数据源
            chart.setCategories(labels)
            chart.dataSource = chartData

            //数据轴最大值
            chart.dataAxis.setAxisMax(100.0)
            //数据轴刻度间隔
            chart.dataAxis.axisSteps = 10.0

            //背景网格
            chart.plotGrid.showHorizontalLines()
            //chart.getPlotGrid().showVerticalLines();
            chart.plotGrid.showEvenRowBgColor()
            chart.plotGrid.showOddRowBgColor()
            chart.plotGrid.horizontalLinePaint.strokeWidth = 2f
            chart.plotGrid.horizontalLineStyle = XEnum.LineStyle.DASH
            chart.plotGrid.verticalLineStyle = XEnum.LineStyle.DOT
            chart.plotGrid.horizontalLinePaint.color = Color.RED
            chart.plotGrid.verticalLinePaint.color = Color.BLUE
            chart.setTitle("折线图(Line Chart)")
            chart.addSubtitle("(XCL-Charts Demo)")
            chart.axisTitle.lowerTitle = "(年份)"

            //激活点击监听
            chart.ActiveListenItemClick()
            //为了让触发更灵敏，可以扩大5px的点击监听范围
            chart.extPointClickRange(5)
            chart.showClikedFocus()

            //绘制十字交叉线
            chart.showDyLine()
            chart.dyLine.dyLineStyle = XEnum.DyLineStyle.Vertical

            /*			
			//想隐藏轴的可以下面的函数来隐藏
			chart.getDataAxis().hide();
			chart.getCategoryAxis().hide();
			//想设置刻度线属性的可用下面函数
			chart.getDataAxis().getTickMarksPaint()
			chart.getCategoryAxis().getTickMarksPaint()
			//想设置刻度线标签属性的可用下面函数 
			chart.getDataAxis().getAxisTickLabelPaint()	
			chart.getCategoryAxis().getAxisTickLabelPaint()
			*/chart.plotArea.extWidth(100f)

            //调整轴显示位置
            chart.dataAxisLocation = XEnum.AxisLocation.RIGHT
            chart.categoryAxisLocation = XEnum.AxisLocation.TOP

            //收缩绘图区右边分割的范围，让绘图区的线不显示出来
            chart.clipExt.extRight = 0f


            //test x坐标从刻度线而不是轴开始
            //chart.setXCoordFirstTickmarksBegin(true);
            //chart.getCategoryAxis().showTickMarks();
            //chart.getCategoryAxis().setVerticalTickPosition(XEnum.VerticalAlign.MIDDLE);
        } catch (e: Exception) {
            // TODO Auto-generated catch block
            Log.e(TAG, e.toString())
        }
    }

    private fun chartDataSet() {

        //Line 1
        val dataSeries1 = LinkedList<Double>()
        dataSeries1.add(20.0)
        dataSeries1.add(10.0)
        dataSeries1.add(31.0)
        dataSeries1.add(40.0)
        dataSeries1.add(0.0)
        val lineData1 = LineData("方块", dataSeries1, Color.rgb(234, 83, 71))
        lineData1.labelVisible = true
        lineData1.dotStyle = XEnum.DotStyle.RECT
        lineData1.dotLabelPaint.color = Color.BLUE
        lineData1.dotLabelPaint.textSize = 22f
        lineData1.dotLabelPaint.textAlign = Paint.Align.LEFT
        lineData1.itemLabelRotateAngle = 45f
        lineData1.labelOptions.setLabelBoxStyle(XEnum.LabelBoxStyle.TEXT)

        //lineData1.getLabelOptions().

        //lineData1.setDataSet(dataSeries);
        //this.invalidate();

        //Line 2
        val dataSeries2 = LinkedList<Double>()
        dataSeries2.add(30.0)
        dataSeries2.add(42.0)
        dataSeries2.add(0.0)
        dataSeries2.add(60.0)
        dataSeries2.add(40.0)
        val lineData2 = LineData("圆环", dataSeries2, Color.rgb(75, 166, 51))
        lineData2.dotStyle = XEnum.DotStyle.RING
        lineData2.plotLine.dotPaint.color = Color.RED
        lineData2.labelVisible = true
        lineData2.plotLine.plotDot.ringInnerColor = Color.GREEN
        lineData2.lineStyle = XEnum.LineStyle.DASH

        // 设置点大小
        //lineData2.getPlotLine().getPlotDot().setDotRadius(radius);

        //Line 3
        val dataSeries3 = LinkedList<Double>()
        dataSeries3.add(65.0)
        dataSeries3.add(75.0)
        dataSeries3.add(55.0)
        dataSeries3.add(65.0)
        dataSeries3.add(95.0)
        val lineData3 = LineData("圆点", dataSeries3, Color.rgb(123, 89, 168))
        lineData3.dotStyle = XEnum.DotStyle.DOT
        lineData3.setDotRadius(20)
        //lineData3.setLabelVisible(true);
        //lineData3.getDotLabelPaint().setTextAlign(Align.CENTER);				

        //Line 4
        val dataSeries4 = LinkedList<Double>()
        dataSeries4.add(50.0)
        dataSeries4.add(60.0)
        dataSeries4.add(80.0)
        dataSeries4.add(84.0)
        dataSeries4.add(90.0)
        val lineData4 = LineData("棱形", dataSeries4, Color.rgb(84, 206, 231))
        lineData4.dotStyle = XEnum.DotStyle.PRISMATIC
        //把线弄细点
        lineData4.linePaint.strokeWidth = 2f
        lineData4.labelOptions.setLabelBoxStyle(XEnum.LabelBoxStyle.CIRCLE)
        lineData4.labelOptions.box.backgroundPaint.color = Color.GREEN
        lineData4.labelVisible = true

        //Line 5
        val valuesE = LinkedList<Double>()
        valuesE.add(0.0)
        valuesE.add(80.0)
        valuesE.add(85.0)
        valuesE.add(90.0)
        val lineData5 = LineData("定制", valuesE, Color.rgb(234, 142, 43))
        lineData5.setDotRadius(15)
        lineData5.dotStyle = XEnum.DotStyle.TRIANGLE

        //Line 2
        val dataSeries6 = LinkedList<Double>()
        dataSeries6.add(50.0)
        dataSeries6.add(52.0)
        dataSeries6.add(53.0)
        dataSeries6.add(55.0)
        dataSeries6.add(40.0)
        val lineData6 = LineData("圆环2", dataSeries6, Color.rgb(75, 166, 51))
        lineData6.dotStyle = XEnum.DotStyle.RING2
        lineData6.plotLine.dotPaint.color = Color.RED
        lineData6.labelVisible = true
        //lineData6.getPlotLine().getPlotDot().setRingInnerColor(Color.GREEN);
        //lineData6.getPlotLine().getPlotDot().setRing2InnerColor(Color.GREEN);
        //lineData6.setLineStyle(XEnum.LineStyle.DASH);
        lineData6.dotLabelPaint.color = Color.rgb(212, 64, 39)
        lineData6.labelOptions.box.backgroundPaint.color = Color.rgb(57, 172, 241)
        lineData6.labelOptions.box.setBorderLineColor(Color.YELLOW)
        chartData.add(lineData1)
        chartData.add(lineData2)
        chartData.add(lineData3)
        chartData.add(lineData4)
        chartData.add(lineData5)
        chartData.add(lineData6)
    }

    private fun chartLabels() {
        labels.add("2010")
        labels.add("2011")
        labels.add("2012")
        labels.add("2013")
        labels.add("2014")
    }

    override fun render(canvas: Canvas) {
        try {
            chart.render(canvas)
        } catch (e: Exception) {
            Log.e(TAG, e.toString())
        }
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        // TODO Auto-generated method stub		
        if (event.action == MotionEvent.ACTION_UP) {
            triggerClick(event.x, event.y)
        }
        super.onTouchEvent(event)
        return true
    }

    //触发监听
    private fun triggerClick(x: Float, y: Float) {

        //交叉线
        if (chart.dyLineVisible) chart.dyLine.setCurrentXY(x, y)
        if (!chart.listenItemClickStatus) {
            //交叉线
            if (chart.dyLineVisible) this.invalidate()
        } else {
            val record = chart.getPositionRecord(x, y)
            if (null == record) {
                if (chart.dyLineVisible) this.invalidate()
                return
            }
            val lData = chartData[record.dataID]
            val lValue = lData.linePoint[record.dataChildID]
            val r = record.radius
            chart.showFocusPointF(record.position, r + r * 0.5f)
            chart.focusPaint.style = Paint.Style.STROKE
            chart.focusPaint.strokeWidth = 3f
            if (record.dataID >= 3) {
                chart.focusPaint.color = Color.BLUE
            } else {
                chart.focusPaint.color = Color.RED
            }

            //在点击处显示tooltip
            mPaintTooltips.color = Color.RED
            //chart.getToolTip().setCurrentXY(x,y);
            chart.toolTip.setCurrentXY(record.position.x, record.position.y)
            chart.toolTip.addToolTip(" Key:" + lData.lineKey, mPaintTooltips)
            chart.toolTip.addToolTip(" Label:" + lData.label, mPaintTooltips)
            chart.toolTip.addToolTip(
                " Current Value:" + java.lang.Double.toString(lValue),
                mPaintTooltips
            )


            //当前标签对应的其它点的值
            val cid = record.dataChildID
            var xLabels = ""
            for (data in chartData) {
                if (cid < data.linePoint.size) {
                    xLabels = java.lang.Double.toString(data.linePoint[cid])
                    chart.toolTip.addToolTip("Line:" + data.label + "," + xLabels, mPaintTooltips)
                }
            }
            this.invalidate()
        }
    }
}